package com.sky.wsp.license.utils;

import org.bouncycastle.util.encoders.Base64;

import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.cert.X509Certificate;

/**
 * @author wangshaopeng@talkweb.com.cn
 * @desccription 签名工具类
 * @date 2024/6/24
 */
public class SignatureUtil {

    /**
     * 签名
     *
     * @param certificate 证书，用于获取证书内公钥支持的签名算法
     * @param privateKey  私钥，用于签名
     * @param content     被签名的内容
     * @return
     */
    public static String sign(X509Certificate certificate, PrivateKey privateKey, String content) {
        try {
            Signature signature = Signature.getInstance(certificate.getSigAlgName());
            signature.initSign(privateKey);
            signature.update(content.getBytes(StandardCharsets.UTF_8));
            byte[] sign = signature.sign();
            String base64String = Base64.toBase64String(sign);
            return base64String;
        } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 验签
     *
     * @param certificate  包含公钥的证书
     * @param content      被签名的内容
     * @param signatureStr 要校验的签名值
     * @return
     */
    public static boolean verify(X509Certificate certificate, String content, String signatureStr) {
        byte[] signatureBytes = Base64.decode(signatureStr);
        try {
            Signature signature = Signature.getInstance(certificate.getSigAlgName());
            /** 这里用到的是证书，实际上用到的也是证书里面的公钥 */
            signature.initVerify(certificate);
            signature.update(content.getBytes(StandardCharsets.UTF_8));
            return signature.verify(signatureBytes);
        } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
            e.printStackTrace();
        }
        return false;
    }
}